<template>
  <div class="page_space">
    <input-card class="mt-15">
      <input-item-select
        v-model="supplyInfo.billNo"
        title="进货单号（选填）"
        tip="请选择进货单号"
        @select="
          goto(
            `/select-purchaseList?intercourseEnterpriseId=${intercourseEnterpriseId}&varietyId=${varietyId}`
          )
        "
        @clear="clearInfo"
      />
      <inputItem
        v-model="supplyInfo.intercourseEnterpriseName"
        :content="supplyInfo.intercourseEnterpriseName"
        title="供货者名称"
        tip="请输入供货者名称"
        type="input"
      />
      <inputItem
        v-model="supplyInfo.field10"
        :content="supplyInfo.field10"
        title="供货者联系方式（选填）"
        tip="请输入供货者联系方式"
        type="input"
      />
      <inputItem
        title="进货日期"
        tip="请选择进货日期"
        type="select"
        :content="supplyInfo.produceDate"
        @select="toSelect('进货日期')"
      />
      <inputItem
        v-model="supplyInfo.secondNum"
        :content="supplyInfo.secondNum"
        title="进货数量"
        tip="请输入采样数量"
        type="number"
        unit="千克"
      />
      <inputItem
        title="产地来源（选填）"
        tip="请选择产地来源"
        type="select"
        :content="supplyInfo.producerName"
        @select="toSelect('产地来源')"
      />
      <inputItem
        v-if="supplyInfo.producerName"
        v-model="supplyInfo.areaName"
        :content="supplyInfo.areaName"
        title="产地（选填）"
        tip="请选择产地"
        type="select"
        @select="toSelect('产地')"
      />
    </input-card>
    <div class="btn_wrap">
      <button class="btn middle default" @click="$router.go(-1)">返回</button>
      <button class="btn middle" @click="submit">确认</button>
    </div>

    <van-popup v-model="show" position="bottom" :round="true">
      <template v-if="active === 0">
        <van-picker
          ref="pickerForOrigin"
          title="选择产地来源"
          show-toolbar
          :columns="['进口', '国产']"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmOrigin">确定</button>
        </div>
      </template>

      <!-- 选择日期 -->
      <template v-if="active === 1">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="submitTime">确定</button>
        </div>
      </template>

      <!-- 选择产地-->
      <template v-if="active === 2">
        <van-cascader
          v-model="cascaderValue"
          title=""
          :options="places"
          @close="show = false"
          @change="onChange"
          @finish="onFinish"
        />
      </template>
    </van-popup>
  </div>
</template>

<script>
import inputCard from '@/components/input-card/card'
import inputItem from '@/components/input-card/item'
import inputItemSelect from '@/components/input-card/item-select'
import { getAreaList } from '@/api/base'
import { delKeepaliveCache, ParseDate } from '@/utils'
import { store, mutations } from '@/observable'
import { validateContactsTel, validateCount } from '@/utils/validate'

export default {
  name: 'addSupplyInfo',
  components: { inputCard, inputItem, inputItemSelect },
  data() {
    return {
      show: false,
      active: 0,
      // 时间picker
      currentDate: new Date(),
      // 区划 区码
      cascaderValue: '',
      // picker 产地来源
      origin: '',
      // 产地选项
      places: [],
      // 供货信息
      supplyInfo: {
        producer: '', // 进口 TRUE ; 国产 FALSE
        producerName: '', // 来源中文
        field10: '', // 供货者联系方式
        relationBillDetailId: '', // 关联进货单详情id
        billNo: '', // 进货单号
        intercourseEnterpriseName: '', // 供货者名称
        secondNum: '', // 进货数量
        originPlaceInfoName: '', // 区划码
        areaName: '', // 产地名
        produceDate: '' // 进货日期
      },
      intercourseEnterpriseId: '', // 经营主体 id
      varietyId: '' // 样品 varietyId
    }
  },
  beforeRouteLeave(to, from, next) {
    // 返回快检主体 清除缓存
    if (to.name === 'immediateSampling' || to.name === 'editDraft') {
      mutations.setPurchaseInfo({})
      // 销毁组件
      delKeepaliveCache(this)
      console.log('销毁:', to.name)
    }
    next()
  },
  created() {
    this.intercourseEnterpriseId = this.$route.query.intercourseEnterpriseId
    this.varietyId = this.$route.query.varietyId
  },
  async activated() {
    // 获取-编辑的供货信息
    if (this.$route.params.info) {
      // console.log(
      //   'iiii',
      //   JSON.parse(decodeURIComponent(this.$route.params.info))
      // )
      let originInfo = JSON.parse(decodeURIComponent(this.$route.params.info))
      for (let item in originInfo) {
        this.supplyInfo[item] = originInfo[item]
      }
      // 获取编辑的区划
      this.supplyInfo.producerName =
        this.supplyInfo.producer === 'FALSE' ? '国产' : '进口'
      this.origin = this.supplyInfo.producerName
      let parentAreaCode =
        this.supplyInfo.producer === 'FALSE' ? 'CHN' : 'EARTH'
      const { code, data } = await getAreaList({ parentAreaCode })
      if (code === '0') {
        this.places = []
        data.forEach((item) => {
          this.places.push({
            text: item.areaName,
            value: item.areaCode,
            children: this.origin === '进口' ? null : []
          })
        })
      }
    }
    // 获取-进货单号 等信息
    if (JSON.stringify(store.purchaseInfo) !== '{}') {
      let info = store.purchaseInfo
      console.log('info', info)
      for (let item in info) {
        this.supplyInfo[item] = info[item] || ''
      }
      // 选择单号后，带出区划范围
      if (this.supplyInfo.producer) {
        let parentAreaCode =
          this.supplyInfo.producer === 'FALSE' ? 'CHN' : 'EARTH'
        this.origin = this.supplyInfo.producer === 'FALSE' ? '国产' : '进口'
        const { code, data } = await getAreaList({ parentAreaCode })
        if (code === '0') {
          this.places = []
          data.forEach((item) => {
            this.places.push({
              text: item.areaName,
              value: item.areaCode,
              children: this.origin === '进口' ? null : []
            })
          })
        }
      }
    }
  },
  methods: {
    // 清除
    clearInfo() {
      this.supplyInfo = this.$options.data().supplyInfo
      this.origin = ''
      this.places = []
    },
    // 校验
    validate() {
      // 必填项-基本信息
      let requiredList = [
        {
          label: '供货者名称',
          key: 'intercourseEnterpriseName'
        },
        {
          label: '进货日期',
          key: 'produceDate'
        },
        {
          label: '进货数量',
          key: 'secondNum'
        }
      ]
      try {
        requiredList.forEach((item) => {
          let value = this.supplyInfo[item.key] + ''.trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })

        // 正则校验
        if (
          this.supplyInfo.field10 &&
          !validateContactsTel(this.supplyInfo.field10)
        ) {
          throw new Error(`供货者联系方式 格式不正确！`)
        }
        if (!validateCount(this.supplyInfo.secondNum)) {
          throw new Error(`进货数量 格式不正确！`)
        }

        return true
      } catch (e) {
        this.$toast(e.message)
      }
    },
    // 提交
    submit() {
      if (!this.validate()) return false
      mutations.setSupplyInfo(this.supplyInfo)
      // console.log('hhhh', this.supplyInfo)
      mutations.setPurchaseInfo({})
      // 销毁组件
      delKeepaliveCache(this)
      this.$router.go(-1)
    },
    toSelect(e) {
      if (e === '进货单号（选填）') {
        this.goto('/select-purchaseList')
      } else if (e === '进货日期') {
        this.active = 1
      } else if (e === '产地来源') {
        this.active = 0
      } else if (e === '产地') {
        this.active = 2
      }
      this.show = true
    },
    // 确定-进货时间
    submitTime() {
      this.supplyInfo.produceDate = ParseDate(this.currentDate)
      this.show = false
    },
    // 选择产地来源
    async confirmOrigin() {
      // 初始化
      this.supplyInfo.areaName = ''
      this.supplyInfo.originPlaceInfoName = ''

      this.origin = this.$refs.pickerForOrigin.getValues()[0]
      this.supplyInfo.producerName = this.origin
      let parentAreaCode = ''
      if (this.origin === '进口') {
        parentAreaCode = 'EARTH'
        this.supplyInfo.producer = 'TRUE'
      } else {
        parentAreaCode = 'CHN'
        this.supplyInfo.producer = 'FALSE'
      }
      this.show = false
      const { code, data } = await getAreaList({ parentAreaCode })
      if (code === '0') {
        this.places = []
        data.forEach((item) => {
          this.places.push({
            text: item.areaName,
            value: item.areaCode,
            children: this.origin === '进口' ? null : []
          })
        })
      }
    },
    // 检测区划改变
    async onChange({ value, selectedOptions, tabIndex }) {
      if (this.origin === '进口' || tabIndex > 2) return
      // console.log(value, selectedOptions, tabIndex)
      const { code, data } = await getAreaList({
        parentAreaCode: value
      })
      let placeIndex = ''
      let target = {}

      if (tabIndex > 0) {
        for (let i = 0; i <= tabIndex; i++) {
          if (selectedOptions[i].parentIndex !== undefined) {
            let parentIndex = selectedOptions[i].parentIndex
            console.log('parentIndex:', parentIndex)
            target = this.places[parentIndex].children
          }
        }
        placeIndex = target.findIndex((item) => item.value === value)
        target = target[placeIndex]
      } else {
        placeIndex = this.places.findIndex((item) => item.value === value)
        target = this.places[placeIndex]
      }

      if (code === '0') {
        data.forEach((item) => {
          if (tabIndex < 1) {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              children: [],
              parentIndex: placeIndex
            })
          } else {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              parentIndex: placeIndex
            })
          }
        })
      }
    },
    // 区划完成
    onFinish({ selectedOptions }) {
      this.supplyInfo.areaName =
        selectedOptions.map((option) => option.text).join('') || ''
      // 获取区划码
      this.supplyInfo.originPlaceInfoName =
        selectedOptions[selectedOptions.length - 1].value
      console.log('finish')
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
